package org.example.utils;

import lombok.extern.slf4j.Slf4j;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Map;

@Component
@Slf4j
public class OkHttpUtil {

    @Autowired
    private OkHttpClient okHttpClient;
    /**
     * get
     *
     * @param url     请求的url
     * @param queries 请求的参数，在浏览器？后面的数据，没有可以传null
     * @return
     */
    public String get(String url, Map<String, String> queries) {
        String responseBody = "";
        StringBuilder sb = new StringBuilder(url);
        if (queries != null && queries.keySet().size() > 0) {
            boolean firstFlag = true;
            for (Map.Entry<String, String> entry : queries.entrySet()) {
                if (firstFlag) {
                    sb.append("?").append(entry.getKey()).append("=").append(entry.getValue());
                    firstFlag = false;
                } else {
                    sb.append("&" + entry.getKey() + "=" + entry.getValue());
                }
            }
        }
        Request request = new Request
                .Builder()
                .url(sb.toString())
                .build();
        return getString(responseBody, request);
    }
    /**
     * post
     *
     * @param url    请求的url
     * @return
     */
    public String post(String url,String json) {
        String responseBody = "";
        FormBody.Builder builder = new FormBody.Builder();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, json);
        Request request = new Request
                .Builder()
                .url(url)
                .method("POST", body)
                .addHeader("X-Authorization", "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Ik1UaEVOVUpHTkVNMVFURTRNMEZCTWpkQ05UZzVNRFUxUlRVd1FVSkRNRU13UmtGRVFrRXpSZyJ9.eyJodHRwczovL2FwaS5vcGVuYWkuY29tL3Byb2ZpbGUiOnsiZW1haWwiOiJkYW5kb25nZmFuQGdtYWlsLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjp0cnVlfSwiaHR0cHM6Ly9hcGkub3BlbmFpLmNvbS9hdXRoIjp7InVzZXJfaWQiOiJ1c2VyLXdHbjhuaXZmSmpLRmloRkpiWWdwYlRXaSJ9LCJpc3MiOiJodHRwczovL2F1dGgwLm9wZW5haS5jb20vIiwic3ViIjoiZ29vZ2xlLW9hdXRoMnwxMDYxMjQ4NDkxODg5NDgwOTU3MzIiLCJhdWQiOlsiaHR0cHM6Ly9hcGkub3BlbmFpLmNvbS92MSIsImh0dHBzOi8vb3BlbmFpLm9wZW5haS5hdXRoMGFwcC5jb20vdXNlcmluZm8iXSwiaWF0IjoxNjg5NDgwMDAzLCJleHAiOjE2OTA2ODk2MDMsImF6cCI6IlRkSkljYmUxNldvVEh0Tjk1bnl5d2g1RTR5T282SXRHIiwic2NvcGUiOiJvcGVuaWQgcHJvZmlsZSBlbWFpbCBtb2RlbC5yZWFkIG1vZGVsLnJlcXVlc3Qgb3JnYW5pemF0aW9uLnJlYWQgb3JnYW5pemF0aW9uLndyaXRlIG9mZmxpbmVfYWNjZXNzIn0.xbMAChupaiaRo9dS6ugdhQjvjaj5A8h2i81u2zwle5bdsu54uEMTgV7Wu6vXn9378WNoaC4J5mFk26Gtg5G81M5i1in1XYpj5TdIZLjjXTYRNUI2BVvTPbrTCWqTHw6AHRHxeKNT6lWT2MmOCF2wMDCCuTr3Q58GXP4IYbXwsUwKqzvhV7oAJ72CvlLjWQm_I_Aexx0OQJ5DvMWxPU9tOC6BZC5zMSt-C0hvcCLP3QvYoStHXYvF6zgkKeT_cCI694x-PaB59_JiuLZ5ZFPiUPmmJeuZ3hvATkGNsXU9TsyaLKr3xuhMKZaEjt2hTqiyD5pg-wOv-YMNHi2tx2YyiQ")
                .build();
        return getString(responseBody, request);
    }


    /**
     * post fromdata
     * @param url
     * @param formBody
     * @return
     * @throws IOException
     */
    public String uploadFormData(String url,RequestBody formBody) throws IOException {
        // 发送请求
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();

        try (Response response = okHttpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }

            // 假设你的OkHttpUtil.uploadFormData方法实际上执行了上面的请求，并返回了响应体作为字符串
            String postResponse = response.body().string();
            return postResponse;
        }
    }

    private String getString(String responseBody, Request request) {
        try (Response response = okHttpClient.newCall(request).execute()) {
            int status = response.code();
            if (status == 200) {
                if (response.body() != null) {
                    return response.body().string();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return responseBody;
    }

    /**
     * post 上传文件
     *
     * @param url
     * @param params
     * @param fileType
     * @return
     */
    public String postFile(String url, Map<String, Object> params, String fileType) {
        String responseBody = "";
        MultipartBody.Builder builder = new MultipartBody.Builder();
        //添加参数
        if (params != null && params.keySet().size() > 0) {
            for (String key : params.keySet()) {
                if (params.get(key) instanceof File) {
                    File file = (File) params.get(key);
                    builder.addFormDataPart(key, file.getName(), RequestBody.create(MediaType.parse(fileType), file));
                    continue;
                }
                builder.addFormDataPart(key, params.get(key).toString());
            }
        }
        Request request = new Request
                .Builder()
                .url(url)
                .post(builder.build())
                .build();
        try (Response response = okHttpClient.newCall(request).execute()) {
            int status = response.code();
            if (status == 200) {
                return response.body().string();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return responseBody;
    }
}
